package com.pirestupppai.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.pirestupppai.R;
import com.pirestupppai.adapter.PsListAdapter;
import com.pirestupppai.base.BaseAdapter;
import com.pirestupppai.base.BaseFragment;
import com.pirestupppai.base.BaseStatus;
import com.pirestupppai.bean.MissionData;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.ui.activity.SelectPictureActivity;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.PsListOptionDialog;
import com.pirestupppai.widgets.view.CustomRecyclerView;
import com.pirestupppai.widgets.view.LoadMoreFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.pirestupppai.adapter.PsListAdapter.PS_TYPE_REPLY_NOW;

/**
 * 帮P:进行中,已完成
 *
 * @author: xiaoluo
 * @date: 2017-04-21 16:59
 */
public class PsListFragment extends BaseFragment {

    @BindView(R.id.ps_inprogress_recycler_view)
    CustomRecyclerView recyclerView;

    private LoadMoreFooter mFooterView;
    private PsListAdapter mPsAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 20;
    private boolean hasMore = true;
    private List<MissionData> mPsList = new ArrayList<>();
    private int mType = PsListAdapter.PS_TYPE_NORMAL;
    private String mListType = "pending";
    private boolean isNormal = false;

    public PsListFragment() {

    }

    @SuppressLint("ValidFragment")
    public PsListFragment(boolean normal, int type, String listType) {
        mListType = listType;
        isNormal = normal;
        mType = type;
    }

    @Override
    protected Context getFragmentContext() {
        return getActivity();
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.fragment_ps_list;
    }

    @Override
    protected void initViews() {
        mFooterView = new LoadMoreFooter(mContext);
        mPsAdapter = new PsListAdapter(mContext, mPsList);
        mPsAdapter.addFooterView(mFooterView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setEmptyText("暂时没有任何任务哟");
        recyclerView.getRecyclerView().setLayoutManager(mLinearLayoutManager);
        recyclerView.getRecyclerView().setAdapter(mPsAdapter);
        recyclerView.getRecyclerView().setHasFixedSize(true);
    }

    @Override
    protected void initListeners() {
        // 监听到达底部事件
        recyclerView.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;

                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        getData(BaseStatus.LOADMORE);
                    }
                }
            }
        });

        mPsAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (mPsList.get(position).getAsk_post() == null) {
                    Utils.showToast("原图不存在");
                    return;
                }
                Intent intent = new Intent();
                if (isNormal) {
                    PsListOptionDialog dialog = new PsListOptionDialog(mContext, mPsList.get(position), mType);
                    dialog.show();
                } else {
                    intent.setClass(mContext, SelectPictureActivity.class);
                    intent.putExtra(Constant.IntentKey.RELEASE_TYPE, Constant.SELECT_TYPE_WORK);
                    intent.putExtra(Constant.IntentKey.PS_TYPE, mType);
                    if (mType == PS_TYPE_REPLY_NOW) {
                        intent.putExtra(Constant.IntentKey.PARENT_ID, mPsList.get(position).getAsk_post().getId());
                    } else {
                        intent.putExtra(Constant.IntentKey.PARENT_ID, mPsList.get(position).getId());
                    }
                    mContext.startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void initLogic() {
        getData(BaseStatus.REFRESH);
    }

    /**
     * 获取数据
     */
    private void getData(final BaseStatus status) {
        if (status == BaseStatus.REFRESH) {
            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
            hasMore = true;
            mPage = 1;
        } else {
            mPage++;
        }

        NetworkRequest.getInstance().getMissionList(mListType, mPage, mSize, mContext,
                new TupaiSubscriber<List<MissionData>>(mContext) {
                    @Override
                    protected void requestSuccess(List<MissionData> missionItems) {
                        if (missionItems != null && missionItems.size() != 0) {
                            if (status == BaseStatus.REFRESH) {
                                mPsList.clear();
                                mPsList.addAll(missionItems);
                                mPsAdapter.notifyDataSetChanged();
                            } else {
                                mPsList.addAll(missionItems);
                                mPsAdapter.notifyItemInserted(mPosition);
                            }
                        } else if (status == BaseStatus.REFRESH) {
                            recyclerView.setEmpty();
                        } else {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                        }

                        if (missionItems != null && missionItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        if (status == BaseStatus.LOADMORE) {
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                            mPage--;
                        }
                    }
                });
    }
}
